package com.zlsy.thread.immutable;

/**
 * @author zhouliang
 * @date 2020/8/22 11:48
 * 演示栈封闭的两种情况，基本变量和对象，先演示线程争抢带来的错误结果
 * 然后把变量放到方法内，情况就变了；
 */
public class StackConfinement implements Runnable {

    int index = 0;

    public static void main(String[] args) throws InterruptedException {
        StackConfinement r = new StackConfinement();
        Thread thread1 = new Thread(r);
        Thread thread2 = new Thread(r);

        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

        System.err.println(r.index);
    }

    public void inthrad() {
        //局部变量 放心大胆的使用 不会产生并发安全问题：因为栈内保护的数字是线程安全的
        int neverGoOut = 0;
        for (int i = 0; i < 10000; i++) {
            neverGoOut++;
        }
        System.out.println("栈内保护的数字是线程安全的：" + neverGoOut);
    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            index++;
        }
        inthrad();
    }


}
